package com.yaodian100.ec.campaign.web;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;

import com.yaodian100.core.admin.utils.AdminHelper;
import com.yaodian100.core.common.dao.impl.CommonCriteria;
import com.yaodian100.core.common.utils.DateUtil;
import com.yaodian100.core.menu.entity.Menu;
import com.yaodian100.core.menu.service.MenuService;
import com.yaodian100.ec.campaign.entity.Campaign;
import com.yaodian100.ec.campaign.entity.CampaignExtend;
import com.yaodian100.ec.campaign.entity.Campaign.Range;
import com.yaodian100.ec.campaign.service.CampaignService;
import com.yaodian100.ec.category.entity.Category;
import com.yaodian100.ec.category.service.CategoryService;
import com.yaodian100.ec.common.EcConstant;
import com.yaodian100.ec.common.web.AbstractAction;
import com.yaodian100.ec.product.entity.Product;
import com.yaodian100.ec.product.service.ProductService;

/**
 * @author eric.chen
 * 
 */
public class CampaignAction extends AbstractAction {

	private static final long serialVersionUID = 178887580319281383L;
	@Autowired
	private CampaignService campaignService;
	@Autowired
	private CategoryService categoryService;
	@Autowired
	private ProductService productService;
	@Autowired
	private MenuService menuService;

	/**
	 * 活动集合物件 Campaign Entity List
	 */
	private List<Campaign> campaignList;

	/**
	 * 活动物件 Campaign Entity
	 */
	private Campaign campaign;
	private String uuid;
	private String startDate;
	private String startTime;
	private String endDate;
	private String endTime;
	private int operation;
	private String rangeExtend;
	private String redRange;
	private String greenRange;
	private boolean ignoreCookie;
	private List rangeExtendObject = new ArrayList();
	private List redRangeExtendObject = new ArrayList();
	private List greenRangeExtendObject = new ArrayList();

	/* 搜寻条件 */
	private List<Campaign.Range> paramRanges = Arrays.asList(Campaign.Range.Order, Campaign.Range.Category,
			Campaign.Range.Product, Campaign.Range.RedGreenCategory);
	private Campaign.Type paramTypes;
	private String paramName;
	private Date paramStartDateTime = new Date();
	private Date paramEndDateTime;
	private String paramCookie;
	private String paramDomain;
	private String[] paramEnable = new String[] { "true", "false" };

	/* 选单 */
	private final List<Campaign.Range> menuRange = Arrays.asList(Campaign.Range.Order, Campaign.Range.Category,
			Campaign.Range.Product, Campaign.Range.RedGreenCategory);
	private final List<Campaign.Type> menuType = Arrays.asList(Campaign.Type.C01, Campaign.Type.C02, Campaign.Type.C03,
			Campaign.Type.M01, Campaign.Type.M02, Campaign.Type.M03, Campaign.Type.M04);
	private Menu menuDomain;
	private Menu menuChannel;
	private Menu menuBudget;

	private Campaign activateCampaign;

	/**
	 * @return the campaign
	 */
	public Campaign getCampaign() {
		return campaign;
	}

	/**
	 * @return the campaignList
	 */
	public List<Campaign> getCampaignList() {
		return campaignList;
	}

	/**
	 * @return the rangeExtendObject
	 */
	public List getRangeExtendObject() {
		return rangeExtendObject;
	}

	/**
	 * @return the menuBudget
	 */
	public Menu getMenuBudget() {
		return menuBudget;
	}

	/**
	 * @return the ignoreCookie
	 */
	public boolean isIgnoreCookie() {
		return ignoreCookie;
	}

	/**
	 * @param ignoreCookie the ignoreCookie to set
	 */
	public void setIgnoreCookie(boolean ignoreCookie) {
		this.ignoreCookie = ignoreCookie;
	}

	/**
	 * @return the operation
	 */
	public int getOperation() {
		return operation;
	}

	/**
	 * @param operation the operation to set
	 */
	public void setOperation(int operation) {
		this.operation = operation;
	}

	/**
	 * @return the rangeExtend
	 */
	public String getRangeExtend() {
		return rangeExtend;
	}

	/**
	 * @param rangeExtend the rangeExtend to set
	 */
	public void setRangeExtend(String rangeExtend) {
		this.rangeExtend = rangeExtend;
	}

	/**
	 * @return the endDate
	 */
	public String getEndDate() {
		return endDate;
	}

	/**
	 * @return the endTime
	 */
	public String getEndTime() {
		return endTime;
	}

	/**
	 * @return the menuType
	 */
	public List<Campaign.Type> getMenuType() {
		return menuType;
	}

	/**
	 * @return the paramEnable
	 */
	public String[] getParamEnable() {
		return paramEnable;
	}

	/**
	 * @return the endDateTimeParam
	 */
	public String getParamEndDateTime() {
		if (paramStartDateTime != null) {
			return DateUtil.convertDateToString("yyyy-MM-dd", paramEndDateTime);
		} else {
			return "";
		}
	}

	/**
	 * @return the paramName
	 */
	public String getParamName() {
		return paramName;
	}

	/**
	 * @return the paramStartDateTime
	 */
	public String getParamStartDateTime() {
		if (paramStartDateTime != null) {
			return DateUtil.convertDateToString("yyyy-MM-dd", paramStartDateTime);
		} else {
			return "";
		}
	}

	/**
	 * @return the startDate
	 */
	public String getStartDate() {
		return startDate;
	}

	/**
	 * @return the startTime
	 */
	public String getStartTime() {
		return startTime;
	}

	/**
	 * @return the menuRange
	 */
	public List<Campaign.Range> getMenuRange() {
		return menuRange;
	}

	/**
	 * @return the uuid
	 */
	public String getUuid() {
		return uuid;
	}

	/**
	 * @return the paramRanges
	 */
	public List<Campaign.Range> getParamRanges() {
		return paramRanges;
	}

	/**
	 * @param paramRanges the paramRanges to set
	 */
	public void setParamRanges(List<Campaign.Range> paramRanges) {
		this.paramRanges = paramRanges;
	}

	/**
	 * @param endDate the endDate to set
	 */
	public void setEndDate(String endDate) {
		this.endDate = endDate;
	}

	/**
	 * @param endTime the endTime to set
	 */
	public void setEndTime(String endTime) {
		this.endTime = endTime;
	}

	/**
	 * @param paramEnable the paramEnable to set
	 */
	public void setParamEnable(String[] paramEnable) {
		this.paramEnable = paramEnable;
	}

	/**
	 * @param endDateTimeParam the endDateTimeParam to set
	 */
	public void setParamEndDateTime(String endDateTimeParam) {
		if (StringUtils.isNotBlank(endDateTimeParam)) {
			if (endDateTimeParam.indexOf("/") != -1) {
				this.paramEndDateTime = DateUtil.convertStringToDate("yyyy/MM/dd", endDateTimeParam);
			} else if (endDateTimeParam.indexOf("-") != -1) {
				this.paramEndDateTime = DateUtil.convertStringToDate("yyyy-MM-dd", endDateTimeParam);
			} else {
				this.paramEndDateTime = DateUtil.convertStringToDate(endDateTimeParam);
			}
		} else {
			this.paramEndDateTime = null;
		}
	}

	/**
	 * @return the paramCookie
	 */
	public String getParamCookie() {
		return paramCookie;
	}

	/**
	 * @param paramCookie the paramCookie to set
	 */
	public void setParamCookie(String paramCookie) {
		this.paramCookie = paramCookie;
	}

	/**
	 * @return the paramDomain
	 */
	public String getParamDomain() {
		return paramDomain;
	}

	/**
	 * @param paramDomain the paramDomain to set
	 */
	public void setParamDomain(String paramDomain) {
		this.paramDomain = paramDomain;
	}

	/**
	 * @param paramName the paramName to set
	 */
	public void setParamName(String paramName) {
		this.paramName = paramName;
	}

	/**
	 * @param paramStartDateTime the paramStartDateTime to set
	 */
	public void setParamStartDateTime(String paramStartDateTime) {
		if (StringUtils.isNotBlank(paramStartDateTime)) {
			if (paramStartDateTime.indexOf("/") != -1) {
				this.paramStartDateTime = DateUtil.convertStringToDate("yyyy/MM/dd", paramStartDateTime);
			} else if (paramStartDateTime.indexOf("-") != -1) {
				this.paramStartDateTime = DateUtil.convertStringToDate("yyyy-MM-dd", paramStartDateTime);
			} else {
				this.paramStartDateTime = DateUtil.convertStringToDate(paramStartDateTime);
			}
		} else {
			this.paramStartDateTime = null;
		}
	}

	/**
	 * @param startDate the startDate to set
	 */
	public void setStartDate(String startDate) {
		this.startDate = startDate;
	}

	/**
	 * @param startTime the startTime to set
	 */
	public void setStartTime(String startTime) {
		this.startTime = startTime;
	}

	/**
	 * @param uuid the uuid to set
	 */
	public void setUuid(String uuid) {
		this.uuid = uuid;
	}

	/**
	 * @return the menuDomain
	 */
	public Menu getMenuDomain() {
		return menuDomain;
	}

	/**
	 * @return the menuChannel
	 */
	public Menu getMenuChannel() {
		return menuChannel;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.yaodian100.ec.common.web.AbstractAction#prepare()
	 */
	@Override
	public void prepare() throws Exception {
		super.prepare();
		if (menuChannel == null) {
			menuChannel = menuService.get("Channel.Name").clone();
			menuChannel.addOption("yaodian100", "耀点100");
		}
		if (menuDomain == null) {
			menuDomain = menuService.get("Site.domain");
		}
		if (menuBudget == null) {
			menuBudget = menuService.get("Budget");
		}
	}

	/**
	 * 储存行销活动资料
	 * 
	 * @return
	 * @throws Exception
	 */
	public String save() {
		try {
			if (!AdminHelper.hasPermission("GROUP_A-50-100-300,ROLE_MM")) {
				addActionError("权限不足，您无权限变更！");
				return "list";
			}
			if (campaign != null) {
				if (campaign.getUuid() != null && !campaign.getUuid().equals(uuid)) {
					addActionError("资料异动错误, 回覆原始资料, 请勿同时操作两视窗");
					campaign = campaignService.get(uuid);
					return "edit";
				}
				rangeExtendObject.clear();
				redRangeExtendObject.clear();
				greenRangeExtendObject.clear();
				campaign.getRangeExtList().clear();
				campaign.setRedRange("");
				campaign.setGreenRange("");

				campaign.setCampaignDesc(StringUtils.replace(campaign.getCampaignDesc(), "\n", "<br/>"));
				campaign.setCampaignDetail(StringUtils.replace(campaign.getCampaignDetail(), "\n", "<br/>"));
				campaign.setStartDateTime(DateUtil.convertStringToDate(EcConstant.PATTERN_TIMESTAMP_HH_MM, startDate + " "
						+ startTime));
				campaign.setEndDateTime(DateUtil.convertStringToDate(EcConstant.PATTERN_TIMESTAMP_HH_MM, endDate + " "
						+ endTime));
				campaign.setEndDateTime(DateUtil.getLastTimestamp(Calendar.MINUTE, campaign.getEndDateTime()));
				if (StringUtils.isNotBlank(greenRange) && StringUtils.isNotBlank(redRange)
						&& Campaign.Range.RedGreenCategory.equals(campaign.getRange())) {// 紅綠標
					List redList = new ArrayList();
					List greenList = new ArrayList();
					String[] red = StringUtils.split(redRange, ",");
					String[] green = StringUtils.split(greenRange, ",");
					for (String r : red) {
						r = StringUtils.remove(r, System.getProperty("line.separator"));
						Category c = categoryService.get(Long.valueOf(StringUtils.trim(r)));
						if (c == null) {
							addActionError("活动分類" + r + "不存在");
							return "edit";
						}
						redList.add(c.getCategoryPath());
						redRangeExtendObject.add(c);
						campaign.getRangeExtList().add(c.getCategoryPath());
					}
					for (String g : green) {
						g = StringUtils.remove(g, System.getProperty("line.separator"));
						Category c = categoryService.get(Long.valueOf(StringUtils.trim(g)));
						if (c == null) {
							addActionError("活动分類" + g + "不存在");
							return "edit";
						}
						greenList.add(c.getCategoryPath());
						greenRangeExtendObject.add(c);
						campaign.getRangeExtList().add(c.getCategoryPath());
					}
					campaign.setRedRange(StringUtils.join(redList, ","));
					campaign.setGreenRange(StringUtils.join(greenList, ","));
				}
				if (StringUtils.isNotBlank(rangeExtend)) {
					if (Campaign.Range.Category.equals(campaign.getRange())) {
						String[] idArray = StringUtils.split(rangeExtend, ",");
						campaign.getRangeExtList().clear();
						for (String id : idArray) {
							id = StringUtils.remove(id, System.getProperty("line.separator"));
							Category c = categoryService.get(Long.valueOf(StringUtils.trim(id)));
							if (c == null) {
								addActionError("活动分類" + id + "不存在");
								return "edit";
							}
							rangeExtendObject.add(c);
							campaign.getRangeExtList().add(c.getCategoryPath());
						}
					} else if (Campaign.Range.Product.equals(campaign.getRange())) {
						campaign.getRangeExtList().clear();
						String[] idArray = StringUtils.split(rangeExtend, ",");
						for (String id : idArray) {
							Product p = productService.get(id);
							if (p == null) {
								addActionError("活动商品" + id + "不存在");
								return "edit";
							} else if (p.getProductType() == 2) {
								addActionError("活动商品(" + p.getProductId() + ")型態不可為贈品");
								return "edit";
							}
							campaign.getRangeExtList().add(id);
							// rangeExtendObject.add(p); // 可能很多不顯示明細
						}
					}
				}
				if (!Range.Order.equals(campaign.getRange()) && campaign.getRangeExtList().size() == 0 && campaign.isEnable()) {
					addActionError("活动" + campaign.getRange().getDesc() + "區間未設定");
					return "edit";
				}

				if (!("M02".equals(campaign.getType().getCode()) || "M03".equals(campaign.getType().getCode()) || "M04"
						.equals(campaign.getType().getCode()))) {
					// 应当有一条以上的活动
					if (campaign.getTypeExtends().size() == 0) {
						addActionError("未设定活动内容");
						return "edit";
					}
					int qty = 0;
					BigDecimal amount = BigDecimal.ZERO;
					for (CampaignExtend ce : campaign.getTypeExtends()) {
						int index = campaign.getTypeExtends().indexOf(ce) + 1;
						ce.getMinOrderAmount().setScale(1);
						ce.getMaxOrderAmount().setScale(1);

						if (StringUtils.isBlank(ce.getCampaignTypeExtension())) {
							addActionError("活动内容不可为空, 第" + index + "笔");
							return "edit";
						}
						if (Campaign.Type.C01.equals(campaign.getType()) || Campaign.Type.C02.equals(campaign.getType())) {
							if (Campaign.Type.C01.equals(campaign.getType())) {
								int discount = Integer.parseInt(ce.getCampaignTypeExtension());
								if (discount < 50 || discount >= 100) {
									addActionError("活动折扣应大于50小于100, 第" + index + "笔");
									return "edit";
								}
							}
							if (!NumberUtils.isNumber(ce.getCampaignTypeExtension())) {
								addActionError("活动内容需为数字, 第" + index + "笔");
								return "edit";
							}
							if (Integer.parseInt(ce.getCampaignTypeExtension()) <= 0) {
								addActionError("活动内容需为正整数, 第" + index + "笔");
								return "edit";
							}
						} else if (Campaign.Type.C03.equals(campaign.getType())) {
							Product p = productService.get(ce.getCampaignTypeExtension());
							if (p == null || "Y".equals(p.getIsDelete())) {
								addActionError("赠品不存在");
								return "edit";
							} else if (!(p.getProductType() == 0 || p.getProductType() == 2)) {
								addActionError("赠品型態必須為主商品或赠品");
								return "edit";
							}
							if (!Campaign.Range.Product.equals(campaign.getRange())) {
								addActionError("赠品限定使用指定商品");
								return "edit";
							} else {
								for (String pId : campaign.getRangeExtList()) {
									Product selPro = productService.get(pId);
									if ("Y".equals(selPro.getIsScm()) && !selPro.getSupplierId().equals(p.getSupplierId())) {
										addActionError("赠品與主商品(" + pId + ")供應商不同");
										return "edit";
									}
								}
							}
						}
						if (!"M01".equals(campaign.getType().getCode())) {
							if (index != 1 && ce.getMinQty() != 0 && (qty + 1 != ce.getMinQty())) {
								addActionError("数量设定错误, 数量不连贯, 第" + index + "笔, 最低数量應為" + (qty + 1));
								return "edit";
							}

							if (ce.getMinQty() > ce.getMaxQty()) {
								addActionError("数量设定错误, 小到大, 第" + index + "笔");
								return "edit";
							}
						}
						qty = ce.getMaxQty();

						if (index != 1 && ce.getMinOrderAmount().compareTo(BigDecimal.ZERO) != 0
								&& (amount.add(new BigDecimal("0.1")).compareTo(ce.getMinOrderAmount())) != 0) {
							addActionError("订单价格设定错误, 价格不连贯, 第" + index + "笔, 最低金額應為" + amount.add(new BigDecimal("0.1")));
							return "edit";
						}
						if (ce.getMinOrderAmount().compareTo(ce.getMaxOrderAmount()) > 0) {
							addActionError("订单价格大小设定错误, 小到大, 第" + index + "笔");
							return "edit";
						}
						amount = ce.getMaxOrderAmount();

						if ("M01".equals(campaign.getType().getCode())) {// 会员积分发送检查
							ce.setUpperLimit(!(StringUtils.isBlank(ce.getBonusLimit()) || "-1".equals(ce.getBonusLimit())));
						}
					}

					if (amount.compareTo(CampaignExtend.MAX_AMOUNT) != 0) {
						addActionError("订单价格区间最后请设 " + CampaignExtend.MAX_AMOUNT);
						return "edit";
					}

					if (!"M01".equals(campaign.getType().getCode())) {
						if (qty != CampaignExtend.MAX_QTY) {
							addActionError("数量区间最后请设 " + CampaignExtend.MAX_QTY);
							return "edit";
						}
					}
				} else {
					// 会员积分折抵, 会员登录发送积分活动不需 CampaignExtend
					campaign.setTypeExtends(null);
				}

				if (campaign.isEnable()) {
					if (!Range.Order.equals(campaign.getRange()) && StringUtils.isBlank(campaign.getRangeExt())) {
						addActionError("活动範圍必填");
						return edit();
					}

					CommonCriteria cri = new CommonCriteria();
					cri.addLe("startDateTime", campaign.getEndDateTime());
					cri.addGe("endDateTime", campaign.getStartDateTime());
					cri.addEq("range", campaign.getRange());
					cri.addEq("domain", campaign.getDomain());
					cri.addEq("enable", true);
					if (campaign.getUuid() != null) {
						cri.addNe("uuid", campaign.getUuid());
					}

					List<Campaign> otherCampaigns = campaignService.getList(0, -1, cri, null);
					for (Campaign c : otherCampaigns) {
						if (Campaign.Range.Category.equals(campaign.getRange())) {
							logger.debug("compare campaign, uuid:{}, name:{}", c.getUuid(), c.getCampaignName());
							for (String c1Path : c.getRangeExtList()) {
								c1Path = c1Path + "/";
								for (String c2Path : campaign.getRangeExtList()) {
									c2Path = c2Path + "/";
									if (c2Path.startsWith(c1Path) || c1Path.startsWith(c2Path)) {
										addActionError("重覆活动,路徑: " + c2Path + ", 活动名称:" + c.getCampaignName());
										logger.warn("重覆活动, uuid:{}, c1Path:{}, c2Path:{}", new Object[] { c.getUuid(), c1Path, c2Path });
										// return edit();
									} else {
										logger.debug("skip: c1Path:{}, c2Path:{}", c1Path, c2Path);
									}
								}
							}
						} else if (Campaign.Range.Product.equals(campaign.getRange())) {
							for (String pId : c.getRangeExtList()) {
								Product p = productService.get(pId);
								if (p == null) {
									addActionError("活动商品: " + pId + "不存在");
									logger.warn("活动商品: {} 不存在, 活动ID: {}", new Object[] { pId, c.getUuid() });
									return edit();
								}
								if (campaign.getRangeExtList().contains(pId)) {
									addActionError("重覆活动, 商品: " + pId + ", 活动名称:" + c.getCampaignName());
									logger.warn("重覆活动, uuid:{}, pId:{}", new Object[] { c.getUuid(), pId });
									// return edit();
								}
							}
						} else if (Campaign.Range.Order.equals(campaign.getRange())) {
							addActionError("重覆活动, 活动名称:" + c.getCampaignName() + ", 活動期間:"
									+ DateUtil.convertDateToString(c.getStartDateTime()) + "~"
									+ DateUtil.convertDateToString(c.getEndDateTime()));
							logger.warn("重覆活动, uuid:{}", c.getUuid());
							// return edit();
						}
					}
				}
				if (ignoreCookie) {
					campaign.setCookie(null);
				} else if (campaign.getCookieArray().size() == 0) {
					addActionError("特定渠道活動需指定一個以上渠道");
					return edit();
				}
				campaignService.save(campaign);
			} else {
				addActionError("活动不存在");
				return search();
			}
		} catch (Exception e) {
			addActionError("储存失败：" + e.getMessage());
			e.printStackTrace();
			return "edit";
		}
		return "view";
	}

	public String search() {
		try {
			CommonCriteria cri = new CommonCriteria();
			if (StringUtils.isNotBlank(paramName)) {
				cri.addRlike("campaignName", paramName);
			}
			if (paramStartDateTime != null) {
				cri.addGe("endDateTime", DateUtil.getFirstTimestamp(Calendar.DATE, paramStartDateTime));
			}
			if (paramEndDateTime != null) {
				cri.addLe("startDateTime", DateUtil.getLastTimestamp(Calendar.DATE, paramEndDateTime));
			}
			if (paramTypes != null) {
				cri.addEq("type", paramTypes);
			}
			if (paramRanges != null && paramRanges.size() > 0) {
				cri.addIn("range", paramRanges);
			}
			if (paramEnable != null && paramEnable.length == 1) {
				cri.addEq("enable", Boolean.parseBoolean(paramEnable[0]));
			}
			if (StringUtils.isNotBlank(paramCookie)) {
				cri.addEq("cookie", paramCookie);
			}
			if (StringUtils.isNotBlank(paramDomain)) {
				cri.addEq("domain", paramDomain);
			}

			int entitySize = campaignService.getListSize(cri).intValue();
			getPager().setTotalSize(entitySize);
			campaignList = campaignService.getList(getPager().getCurrentPage() * getPager().getPageRecord(), getPager()
					.getPageRecord(), cri, new String[] { "startDateTime", "campaignName asc", "uuid" });

			activateCampaign = null;
			if (paramTypes != null && StringUtils.isNotBlank(paramDomain)) {
				Map<String, String> options = new HashMap<String, String>();
				options.put("domain", paramDomain);
				if ("M01".equals(paramTypes.getCode())) {
					activateCampaign = campaignService.getActiveBonusCampaignByM01(options);
				}
				if ("M02".equals(paramTypes.getCode())) {
					activateCampaign = campaignService.getActiveBonusCampaignByM02(options);
				}
				if ("M03".equals(paramTypes.getCode())) {
					activateCampaign = campaignService.getActiveBonusCampaignByM03(options);
				}
			}
		} catch (Exception e) {
			addActionError("搜寻失败：" + e.getMessage());
			e.printStackTrace();
		}
		return "list";
	}

	/**
	 * 检视活动资料
	 * 
	 * @return
	 */
	public String view() {
		if (StringUtils.isNotBlank(uuid)) {
			campaign = campaignService.get(uuid);
		}
		if (campaign == null) {
			addActionError("活动UUID 有误, 重新选取");
			return search();
		}
		rangeExtendObject.clear();
		redRangeExtendObject.clear();
		greenRangeExtendObject.clear();
		rangeExtend = "";
		redRange = "";
		greenRange = "";
		if (StringUtils.isNotBlank(campaign.getRangeExt())) {
			if (Campaign.Range.Category.equals(campaign.getRange())) {
				List rangeExtendList = new ArrayList();
				String[] pathArray = StringUtils.split(campaign.getRangeExt(), ",");
				for (String path : pathArray) {
					String[] realPath = StringUtils.split(path, "/");
					Category c = categoryService.get(Long.valueOf(realPath[realPath.length - 1]));
					rangeExtendList.add(realPath[realPath.length - 1]);
					rangeExtendObject.add(c);
				}
				rangeExtend = StringUtils.join(rangeExtendList, ",");
			} else if (Campaign.Range.RedGreenCategory.equals(campaign.getRange())) {// 紅綠標
				List redList = new ArrayList();
				List greenList = new ArrayList();
				String[] redArray = StringUtils.split(campaign.getRedRange(), ",");
				String[] greenArray = StringUtils.split(campaign.getGreenRange(), ",");
				for (String path : redArray) {
					String[] realPath = StringUtils.split(path, "/");
					Category c = categoryService.get(Long.valueOf(realPath[realPath.length - 1]));
					redList.add(realPath[realPath.length - 1]);
					redRangeExtendObject.add(c);
				}
				redRange = StringUtils.join(redList, ",");
				for (String path : greenArray) {
					String[] realPath = StringUtils.split(path, "/");
					Category c = categoryService.get(Long.valueOf(realPath[realPath.length - 1]));
					greenList.add(realPath[realPath.length - 1]);
					greenRangeExtendObject.add(c);
				}
				greenRange = StringUtils.join(greenList, ",");
			} else if (Campaign.Range.Product.equals(campaign.getRange())) {
				rangeExtend = campaign.getRangeExt();
			}
		}
		if (StringUtils.isBlank(campaign.getCookie())) {
			ignoreCookie = true;
		} else {
			ignoreCookie = false;
		}
		return "view";
	}

	public String list() throws Exception {
		return "list";
	}

	/**
	 * 载入新增活动资料页
	 * 
	 * @return
	 */
	public String add() {
		campaign = new Campaign();
		Calendar cal = DateUtil.getToday();
		cal.add(Calendar.DATE, 7);
		cal.set(Calendar.HOUR_OF_DAY, 0);
		cal.set(Calendar.MINUTE, 0);
		campaign.setStartDateTime(cal.getTime());
		cal.add(Calendar.MONTH, 1);
		campaign.setEndDateTime(DateUtil.getLastTimestamp(Calendar.DATE, cal.getTime()));
		campaign.addTypeExtend(new CampaignExtend());
		return "edit";
	}

	public String delete() {
		try {
			if (!AdminHelper.hasPermission("GROUP_A-50-100-300,ROLE_MM")) {
				addActionError("权限不足，您无权限变更！");
				return "list";
			}
			if (campaign == null) {
				addActionError("活动不存在");
				return search();
			}
			campaignService.delete(campaign);
		} catch (Exception e) {
			addActionError("删除失败：" + e.getMessage());
			e.printStackTrace();
			return "view";
		}
		return search();
	}

	@Override
	public String clone() {
		try {
			if (campaign == null) {
				addActionError("活动不存在");
				return search();
			}
			Campaign tmp = new Campaign();
			BeanUtils.copyProperties(campaign, tmp, new String[] { "uuid", "createDate", "createUser", "modifyUser",
					"modifyDate", "typeExtends", "rangeExtList" });
			for (CampaignExtend ce : campaign.getTypeExtends()) {
				CampaignExtend tmpCe = new CampaignExtend();
				BeanUtils.copyProperties(ce, tmpCe,
						new String[] { "uuid", "createDate", "createUser", "modifyUser", "campaign" });
				tmp.addTypeExtend(tmpCe);
			}
			for (String re : campaign.getRangeExtList()) {
				tmp.getRangeExtList().add(re);
			}
			campaign = tmp;
		} catch (Exception e) {
			addActionError("Clone失败：" + e.getMessage());
			e.printStackTrace();
			return "view";
		}
		return "edit";
	}

	/**
	 * 修改活动资料
	 * 
	 * @return
	 * @throws Exception
	 */
	public String edit() {
		if (campaign == null) {
			addActionError("活动不存在, 重新选取");
			return search();
		}
		campaign.setCampaignDesc(StringUtils.replace(campaign.getCampaignDesc(), "<br/>", "\n"));
		campaign.setCampaignDetail(StringUtils.replace(campaign.getCampaignDetail(), "<br/>", "\n"));

		if (StringUtils.isBlank(campaign.getUuid())) {// 新增
			if ("M01".equals(campaign.getType().getCode())) {
				for (CampaignExtend ce : campaign.getTypeExtends()) {
					ce.setMinQty(1);
					ce.setMaxQty(1);
				}
			}
		}
		return "edit";
	}

	public String addExt() {
		if (campaign == null) {
			addActionError("活动不存在, 重新选取");
			return search();
		}
		CampaignExtend ce = new CampaignExtend();
		CampaignExtend beforeCe;
		if (null == campaign.getTypeExtends() || campaign.getTypeExtends().isEmpty()) {
			if ("M01".equals(campaign.getType().getCode())) {
				ce.setMinQty(1);
				ce.setMaxQty(1);
			}
			campaign.addTypeExtend(ce);
			return "edit";
		}
		if (operation < 0) {
			beforeCe = campaign.getTypeExtends().get(campaign.getTypeExtends().size() - 1);
			if ("M01".equals(campaign.getType().getCode())) { // 会员积分发送
				ce.setMinQty(1);
				ce.setMaxQty(1);
			} else if (beforeCe.getMaxQty() != CampaignExtend.MAX_QTY) {
				ce.setMinQty(beforeCe.getMaxQty() + 1);
			}
			if (beforeCe.getMaxOrderAmount().compareTo(CampaignExtend.MAX_AMOUNT) != 0) {
				ce.setMinOrderAmount(beforeCe.getMaxOrderAmount().add(new BigDecimal("0.1")));
			}
			ce.setCampaignTypeExtension(beforeCe.getCampaignTypeExtension());
			campaign.addTypeExtend(ce);
		} else {
			beforeCe = campaign.getTypeExtends().get(operation - 1);
			if (beforeCe.getMaxQty() != CampaignExtend.MAX_QTY) {
				ce.setMinQty(beforeCe.getMaxQty() + 1);
			}
			if (beforeCe.getMaxOrderAmount().compareTo(CampaignExtend.MAX_AMOUNT) != 0) {
				ce.setMinOrderAmount(beforeCe.getMaxOrderAmount().add(new BigDecimal("0.1")));
			}
			ce.setCampaignTypeExtension(beforeCe.getCampaignTypeExtension());
			campaign.addTypeExtend(operation, ce);
		}
		return "edit";
	}

	public String delExt() {
		if (campaign == null) {
			addActionError("活动不存在, 重新选取");
			return search();
		}
		if (campaign.getTypeExtends().size() == 1) {
			addActionError("活动不可清空");
		} else {
			campaign.getTypeExtends().remove(operation);
		}
		return "edit";
	}

	public String getRedRange() {
		return redRange;
	}

	public void setRedRange(String redRange) {
		this.redRange = redRange;
	}

	public String getGreenRange() {
		return greenRange;
	}

	public void setGreenRange(String greenRange) {
		this.greenRange = greenRange;
	}

	public List getRedRangeExtendObject() {
		return redRangeExtendObject;
	}

	public List getGreenRangeExtendObject() {
		return greenRangeExtendObject;
	}

	public Campaign.Type getParamTypes() {
		return paramTypes;
	}

	public void setParamTypes(Campaign.Type paramTypes) {
		this.paramTypes = paramTypes;
	}

	public Campaign getActivateCampaign() {
		return activateCampaign;
	}

}